var koa = require('koa'),
    path = require('path'),
    koaBody = require('koa-body'),
    koaError = require('koa-onerror'),
    koaNunjucks = require('koa-nunjucks-2'),
    koaRedis = require('koa-redis'),
    koaRequest = require('koa-http-request'),
    session = require('koa-generic-session'),
    route = require('./middleware/route'),
    config = require('./config.json'),
    port =  process.env.PORT || 8090,
    app;

app = koa();
app.debug = config.debug;
app.keys = ['user app is a secret'];
koaError(app);

/*!
 * 启用session服务
 */
if (config.redis) {
    app.use(session({
        store: koaRedis(config.redis)
    }));
}

/*!
 * 提供post获取参数
 */
app.use(koaBody());

/*!
 * 启动Nunjucks模板引擎
 */
app.context.render = koaNunjucks({
    ext: 'html',
    path: path.join(__dirname, './views'),
    nunjucksConfig: {
        noCache: config.debug,
        autoescape: true
    }
});

/*!
 * koa-http-request中间件
 */
app.use(koaRequest());

/*!
 * 路由
 */
app.use(route(config));

app.listen(port);
console.log('server start at port:' + port + ' env:' + app.env);
